using B.S.Domain.Dto.AICustomerServiceDTO;
using B.S.Infratrctrue;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

namespace B.S.Data.MES.API.Services
{
    /// <summary>
    /// 数据查询服务实现
    /// </summary>
    public class DataQueryService : IDataQueryService
    {
        private readonly SysDbcontext _context;
        private readonly ILogger<DataQueryService> _logger;

        public DataQueryService(SysDbcontext context, ILogger<DataQueryService> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 根据用户问题智能查询数据
        /// </summary>
        public async Task<DataQueryResult> QueryDataByQuestion(string userQuestion)
        {
            try
            {
                var question = userQuestion?.ToLower().Trim() ?? "";
                _logger.LogInformation("收到用户问题: {Question}", userQuestion);

                // 分析问题类型并路由到相应的查询方法
                if (ContainsKeywords(question, new[] { "工单", "订单", "生产", "工作订单", "work", "order" }))
                {
                    var workCode = ExtractCode(userQuestion, new[] { "工单", "订单", "编号" });
                    return await GetWorkOrderInfo(workCode);
                }

                if (ContainsKeywords(question, new[] { "物料", "材料", "产品", "material", "product" }))
                {
                    var materialCode = ExtractCode(userQuestion, new[] { "物料", "材料", "编号", "代码" });
                    return await GetMaterialInfo(materialCode);
                }

                if (ContainsKeywords(question, new[] { "客户", "customer", "client", "供应商" }))
                {
                    var customerName = ExtractName(userQuestion, new[] { "客户", "公司", "名称" });
                    return await GetCustomerInfo(customerName);
                }

                if (ContainsKeywords(question, new[] { "仓库", "库存", "warehouse", "stock", "inventory" }))
                {
                    var warehouseName = ExtractName(userQuestion, new[] { "仓库", "库房" });
                    return await GetWarehouseInfo(warehouseName);
                }

                if (ContainsKeywords(question, new[] { "生产线", "产线", "production", "line" }))
                {
                    var lineName = ExtractName(userQuestion, new[] { "生产线", "产线" });
                    return await GetProductionLineInfo(lineName);
                }

                if (ContainsKeywords(question, new[] { "质量", "检验", "quality", "inspect", "examine" }))
                {
                    var examineType = ExtractName(userQuestion, new[] { "检验", "质量", "类型" });
                    return await GetQualityInfo(examineType);
                }

                if (ContainsKeywords(question, new[] { "用户", "账户", "account", "user", "登录" }))
                {
                    var userName = ExtractName(userQuestion, new[] { "用户", "账户", "姓名" });
                    return await GetAccountInfo(userName);
                }

                if (ContainsKeywords(question, new[] { "统计", "数据", "总数", "汇总", "statistics", "summary" }))
                {
                    return await GetSystemStatistics();
                }

                // 如果没有匹配到特定类型，返回系统概览
                return await GetSystemOverview();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据查询失败: {Message}", ex.Message);
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "抱歉，查询数据时出现了错误，请稍后再试。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取工单信息
        /// </summary>
        public async Task<DataQueryResult> GetWorkOrderInfo(string? workCode = null)
        {
            try
            {
                var query = _context.WorkOrders.AsQueryable();

                if (!string.IsNullOrEmpty(workCode))
                {
                    query = query.Where(w => w.WorkCode.Contains(workCode));
                }

                var workOrders = await query
                    .OrderByDescending(w => w.CreateTime)
                    .Take(10)
                    .ToListAsync();

                if (!workOrders.Any())
                {
                    return new DataQueryResult
                    {
                        Success = true,
                        DataCount = 0,
                        Answer = string.IsNullOrEmpty(workCode) 
                            ? "系统中暂无工单数据。" 
                            : $"未找到编号包含 '{workCode}' 的工单。",
                        DataType = "工单信息"
                    };
                }

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = workOrders.Count,
                    DataType = "工单信息",
                    RawData = JsonConvert.SerializeObject(workOrders, Formatting.Indented)
                };

                if (workOrders.Count == 1)
                {
                    var wo = workOrders.First();
                    result.Answer = $"工单信息：\n" +
                                   $"📋 工单编号：{wo.WorkCode}\n" +
                                   $"📦 产品ID：{wo.ProductId}\n" +
                                   $"👥 客户ID：{wo.CustomerId}\n" +
                                   $"📊 数量：{wo.WorkNum}\n" +
                                   $"📅 创建时间：{wo.CreateTime:yyyy-MM-dd HH:mm}\n" +
                                   $"💼 状态：{wo.States}\n" +
                                   $"📝 备注：{wo.Remark}";
                }
                else
                {
                    result.Answer = $"找到 {workOrders.Count} 个工单：\n\n" +
                                   string.Join("\n", workOrders.Select((wo, i) => 
                                       $"{i + 1}. {wo.WorkCode} - 产品ID:{wo.ProductId} (客户ID:{wo.CustomerId})"));
                }

                result.Suggestions = new List<string>
                {
                    "查看具体工单详情",
                    "查询工单状态",
                    "查看生产进度",
                    "查询相关物料信息"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询工单信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "查询工单信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取物料信息
        /// </summary>
        public async Task<DataQueryResult> GetMaterialInfo(string? materialCode = null)
        {
            try
            {
                var query = _context.Product_materials.AsQueryable();

                if (!string.IsNullOrEmpty(materialCode))
                {
                    query = query.Where(m => m.Productcode.Contains(materialCode) || 
                                           m.ProductName.Contains(materialCode));
                }

                var materials = await query
                    .OrderByDescending(m => m.CreateTime)
                    .Take(10)
                    .ToListAsync();

                if (!materials.Any())
                {
                    return new DataQueryResult
                    {
                        Success = true,
                        DataCount = 0,
                        Answer = string.IsNullOrEmpty(materialCode) 
                            ? "系统中暂无物料数据。" 
                            : $"未找到相关的物料信息：'{materialCode}'。",
                        DataType = "物料信息"
                    };
                }

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = materials.Count,
                    DataType = "物料信息",
                    RawData = JsonConvert.SerializeObject(materials, Formatting.Indented)
                };

                if (materials.Count == 1)
                {
                    var material = materials.First();
                    result.Answer = $"物料信息：\n" +
                                   $"🏷️ 物料编号：{material.Productcode}\n" +
                                   $"📦 物料名称：{material.ProductName}\n" +
                                   $"📏 规格型号：{material.specifications}\n" +
                                   $"📊 单位：{material.unit}\n" +
                                   $"📅 创建时间：{material.CreateTime:yyyy-MM-dd}\n" +
                                   $"📝 描述：{material.describe}";
                }
                else
                {
                    result.Answer = $"找到 {materials.Count} 个物料：\n\n" +
                                   string.Join("\n", materials.Select((m, i) => 
                                       $"{i + 1}. {m.Productcode} - {m.ProductName} ({m.specifications})"));
                }

                result.Suggestions = new List<string>
                {
                    "查看物料详细规格",
                    "查询物料库存",
                    "查看物料供应商",
                    "查询相关BOM信息"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询物料信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "查询物料信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        public async Task<DataQueryResult> GetCustomerInfo(string? customerName = null)
        {
            try
            {
                var query = _context.clients.AsQueryable();

                if (!string.IsNullOrEmpty(customerName))
                {
                    query = query.Where(c => c.Customername.Contains(customerName) || 
                                           c.Customercode.Contains(customerName));
                }

                var customers = await query
                    .OrderByDescending(c => c.CreateTime)
                    .Take(10)
                    .ToListAsync();

                if (!customers.Any())
                {
                    return new DataQueryResult
                    {
                        Success = true,
                        DataCount = 0,
                        Answer = string.IsNullOrEmpty(customerName) 
                            ? "系统中暂无客户数据。" 
                            : $"未找到相关的客户信息：'{customerName}'。",
                        DataType = "客户信息"
                    };
                }

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = customers.Count,
                    DataType = "客户信息",
                    RawData = JsonConvert.SerializeObject(customers, Formatting.Indented)
                };

                if (customers.Count == 1)
                {
                    var customer = customers.First();
                    result.Answer = $"客户信息：\n" +
                                   $"🏢 客户编号：{customer.Customercode}\n" +
                                   $"🏷️ 客户名称：{customer.Customername}\n" +
                                   $"📞 联系方式：{customer.ContactinformationofCustomer}\n" +
                                   $"📍 地址：{customer.Customerraddress}\n" +
                                   $"💳 信用代码：{customer.Customercreditcode}\n" +
                                   $"📅 创建时间：{customer.CreateTime:yyyy-MM-dd}\n" +
                                   $"📝 备注：{customer.Customercomments}";
                }
                else
                {
                    result.Answer = $"找到 {customers.Count} 个客户：\n\n" +
                                   string.Join("\n", customers.Select((c, i) => 
                                       $"{i + 1}. {c.Customercode} - {c.Customername} ({c.Customerrabbreviation})"));
                }

                result.Suggestions = new List<string>
                {
                    "查看客户联系方式",
                    "查询客户订单历史",
                    "查看客户合作项目",
                    "查询客户账款信息"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询客户信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "查询客户信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取仓库信息
        /// </summary>
        public async Task<DataQueryResult> GetWarehouseInfo(string? warehouseName = null)
        {
            try
            {
                var query = _context.CangKuinfos.AsQueryable();

                if (!string.IsNullOrEmpty(warehouseName))
                {
                    query = query.Where(w => w.CangName.Contains(warehouseName) || 
                                           w.CangkuNo.Contains(warehouseName));
                }

                var warehouses = await query
                    .OrderBy(w => w.CangkuNo)
                    .Take(10)
                    .ToListAsync();

                if (!warehouses.Any())
                {
                    return new DataQueryResult
                    {
                        Success = true,
                        DataCount = 0,
                        Answer = string.IsNullOrEmpty(warehouseName) 
                            ? "系统中暂无仓库数据。" 
                            : $"未找到相关的仓库信息：'{warehouseName}'。",
                        DataType = "仓库信息"
                    };
                }

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = warehouses.Count,
                    DataType = "仓库信息",
                    RawData = JsonConvert.SerializeObject(warehouses, Formatting.Indented)
                };

                if (warehouses.Count == 1)
                {
                    var warehouse = warehouses.First();
                    result.Answer = $"仓库信息：\n" +
                                   $"🏗️ 仓库编号：{warehouse.CangkuNo}\n" +
                                   $"🏷️ 仓库名称：{warehouse.CangName}\n" +
                                   $"📍 仓库地址：{warehouse.Address}\n" +
                                   $"📝 仓库描述：{warehouse.MShu}\n" +
                                   $"📊 仓库状态：{(warehouse.isDel ? "已停用" : "正常使用")}\n" +
                                   $"📅 创建时间：{warehouse.CreateTime:yyyy-MM-dd}";
                }
                else
                {
                    result.Answer = $"找到 {warehouses.Count} 个仓库：\n\n" +
                                   string.Join("\n", warehouses.Select((w, i) => 
                                       $"{i + 1}. {w.CangkuNo} - {w.CangName} ({w.Address})"));
                }

                result.Suggestions = new List<string>
                {
                    "查看仓库库存详情",
                    "查询仓库区域信息",
                    "查看仓库货位信息",
                    "查询出入库记录"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询仓库信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "查询仓库信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取生产线信息
        /// </summary>
        public async Task<DataQueryResult> GetProductionLineInfo(string? productionLineName = null)
        {
            try
            {
                var query = _context.Production_line_managements.AsQueryable();

                if (!string.IsNullOrEmpty(productionLineName))
                {
                    query = query.Where(p => p.Nameofproductionline.Contains(productionLineName) || 
                                           p.Productionlinenumber.Contains(productionLineName));
                }

                var productionLines = await query
                    .OrderBy(p => p.Productionlinenumber)
                    .Take(10)
                    .ToListAsync();

                if (!productionLines.Any())
                {
                    return new DataQueryResult
                    {
                        Success = true,
                        DataCount = 0,
                        Answer = string.IsNullOrEmpty(productionLineName) 
                            ? "系统中暂无生产线数据。" 
                            : $"未找到相关的生产线信息：'{productionLineName}'。",
                        DataType = "生产线信息"
                    };
                }

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = productionLines.Count,
                    DataType = "生产线信息",
                    RawData = JsonConvert.SerializeObject(productionLines, Formatting.Indented)
                };

                if (productionLines.Count == 1)
                {
                    var line = productionLines.First();
                    result.Answer = $"生产线信息：\n" +
                                   $"🏭 生产线编号：{line.Productionlinenumber}\n" +
                                   $"🏷️ 生产线名称：{line.Nameofproductionline}\n" +
                                   $"📊 生产线状态：{(line.isDel ? "已停用" : "正常运行")}\n" +
                                   $"📅 创建时间：{line.CreateTime:yyyy-MM-dd}\n" +
                                   $"👤 创建人：{line.CreateName}\n" +
                                   $"📝 描述：{line.Descriptionofproductionline}";
                }
                else
                {
                    result.Answer = $"找到 {productionLines.Count} 条生产线：\n\n" +
                                   string.Join("\n", productionLines.Select((p, i) => 
                                       $"{i + 1}. {p.Productionlinenumber} - {p.Nameofproductionline}"));
                }

                result.Suggestions = new List<string>
                {
                    "查看生产线运行状态",
                    "查询生产线产能",
                    "查看生产线工单",
                    "查询生产线设备信息"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询生产线信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "查询生产线信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取质量检验信息
        /// </summary>
        public async Task<DataQueryResult> GetQualityInfo(string? examineType = null)
        {
            try
            {
                var examineTypes = await _context.ExamineTypes
                    .OrderByDescending(e => e.CreateTime)
                    .Take(10)
                    .ToListAsync();

                var examineProjects = await _context.ExamineProjects
                    .OrderByDescending(e => e.CreateTime)
                    .Take(5)
                    .ToListAsync();

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = examineTypes.Count + examineProjects.Count,
                    DataType = "质量检验信息"
                };

                var answer = "质量检验信息概览：\n\n";

                if (examineTypes.Any())
                {
                    answer += "🔍 检验类型：\n";
                    answer += string.Join("\n", examineTypes.Take(5).Select((e, i) => 
                        $"{i + 1}. {e.ExamineName} - {e.ExamineDesc}"));
                    answer += "\n\n";
                }

                if (examineProjects.Any())
                {
                    answer += "📋 检验项目：\n";
                    answer += string.Join("\n", examineProjects.Take(5).Select((p, i) => 
                        $"{i + 1}. {p.ExamineProjectName} - {p.ProjectMethod}"));
                }

                if (!examineTypes.Any() && !examineProjects.Any())
                {
                    answer = "系统中暂无质量检验数据。";
                }

                result.Answer = answer;
                result.Suggestions = new List<string>
                {
                    "查看检验标准",
                    "查询检验记录",
                    "查看不合格品处理",
                    "查询质量统计报表"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询质量检验信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "查询质量检验信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取账户信息
        /// </summary>
        public async Task<DataQueryResult> GetAccountInfo(string? userName = null)
        {
            try
            {
                var query = _context.accounts.AsQueryable();

                if (!string.IsNullOrEmpty(userName))
                {
                    query = query.Where(a => a.UserName.Contains(userName) || 
                                           a.UserNickname.Contains(userName));
                }

                var accounts = await query
                    .Select(a => new { 
                        a.UserId, 
                        a.UserName, 
                        a.UserNickname, 
                        a.CreateTime, 
                        a.CreateName,
                        a.isDel 
                    })
                    .OrderByDescending(a => a.CreateTime)
                    .Take(10)
                    .ToListAsync();

                if (!accounts.Any())
                {
                    return new DataQueryResult
                    {
                        Success = true,
                        DataCount = 0,
                        Answer = string.IsNullOrEmpty(userName) 
                            ? "系统中暂无用户账户数据。" 
                            : $"未找到相关的用户账户：'{userName}'。",
                        DataType = "账户信息"
                    };
                }

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = accounts.Count,
                    DataType = "账户信息",
                    RawData = JsonConvert.SerializeObject(accounts, Formatting.Indented)
                };

                if (accounts.Count == 1)
                {
                    var account = accounts.First();
                    result.Answer = $"用户账户信息：\n" +
                                   $"👤 用户ID：{account.UserId}\n" +
                                   $"🏷️ 用户名：{account.UserName}\n" +
                                   $"📝 昵称：{account.UserNickname}\n" +
                                   $"📊 状态：{(account.isDel ? "已禁用" : "正常")}\n" +
                                   $"📅 创建时间：{account.CreateTime:yyyy-MM-dd HH:mm}\n" +
                                   $"👥 创建人：{account.CreateName}";
                }
                else
                {
                    result.Answer = $"找到 {accounts.Count} 个用户账户：\n\n" +
                                   string.Join("\n", accounts.Select((a, i) => 
                                       $"{i + 1}. {a.UserName} ({a.UserNickname}) - {(a.isDel ? "已禁用" : "正常")}"));
                }

                result.Suggestions = new List<string>
                {
                    "查看用户权限",
                    "查询登录记录",
                    "查看用户角色",
                    "查询操作日志"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询账户信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "查询账户信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取系统统计信息
        /// </summary>
        public async Task<DataQueryResult> GetSystemStatistics()
        {
            try
            {
                var workOrderCount = await _context.WorkOrders.CountAsync();
                var materialCount = await _context.Product_materials.CountAsync();
                var customerCount = await _context.clients.CountAsync();
                var warehouseCount = await _context.CangKuinfos.CountAsync();
                var productionLineCount = await _context.Production_line_managements.CountAsync();
                var accountCount = await _context.accounts.Where(a => !a.isDel).CountAsync();

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = 6,
                    DataType = "系统统计信息",
                    Answer = $"📊 MES系统数据统计：\n\n" +
                            $"📋 工单总数：{workOrderCount:N0} 个\n" +
                            $"📦 物料总数：{materialCount:N0} 个\n" +
                            $"🏢 客户总数：{customerCount:N0} 个\n" +
                            $"🏗️ 仓库总数：{warehouseCount:N0} 个\n" +
                            $"🏭 生产线总数：{productionLineCount:N0} 条\n" +
                            $"👤 活跃用户：{accountCount:N0} 个\n\n" +
                            $"🕐 统计时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
                };

                result.RawData = JsonConvert.SerializeObject(new
                {
                    WorkOrderCount = workOrderCount,
                    MaterialCount = materialCount,
                    CustomerCount = customerCount,
                    WarehouseCount = warehouseCount,
                    ProductionLineCount = productionLineCount,
                    AccountCount = accountCount,
                    StatisticsTime = DateTime.Now
                }, Formatting.Indented);

                result.Suggestions = new List<string>
                {
                    "查看详细数据分析",
                    "查询最近活动记录",
                    "查看系统性能指标",
                    "生成统计报表"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统统计信息失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "获取系统统计信息时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取系统概览
        /// </summary>
        private async Task<DataQueryResult> GetSystemOverview()
        {
            try
            {
                var todayWorkOrders = await _context.WorkOrders
                    .Where(w => w.CreateTime.HasValue && w.CreateTime.Value.Date == DateTime.Today)
                    .CountAsync();

                var recentMaterials = await _context.Product_materials
                    .Where(m => m.CreateTime.HasValue && m.CreateTime.Value >= DateTime.Today.AddDays(-7))
                    .CountAsync();

                var result = new DataQueryResult
                {
                    Success = true,
                    DataCount = 1,
                    DataType = "系统概览",
                    Answer = $"🏭 MES制造执行系统概览：\n\n" +
                            $"欢迎使用MES系统！我可以帮您查询：\n\n" +
                            $"📋 工单信息 - 生产订单、进度跟踪\n" +
                            $"📦 物料信息 - 原材料、产品规格\n" +
                            $"🏢 客户信息 - 客户资料、联系方式\n" +
                            $"🏗️ 仓库信息 - 库存管理、货位信息\n" +
                            $"🏭 生产线信息 - 产线状态、设备信息\n" +
                            $"🔍 质量检验 - 检验标准、质量记录\n" +
                            $"👤 用户账户 - 权限管理、操作记录\n" +
                            $"📊 统计数据 - 系统汇总、数据分析\n\n" +
                            $"📈 今日新增工单：{todayWorkOrders} 个\n" +
                            $"📦 本周新增物料：{recentMaterials} 个\n\n" +
                            $"💬 您可以问我任何关于系统数据的问题！"
                };

                result.Suggestions = new List<string>
                {
                    "查看今日工单列表",
                    "查询系统统计数据",
                    "查看最新物料信息",
                    "了解系统功能介绍"
                };

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统概览失败");
                return new DataQueryResult
                {
                    Success = false,
                    Answer = "获取系统概览时出现错误。",
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 检查是否包含关键词
        /// </summary>
        private static bool ContainsKeywords(string text, string[] keywords)
        {
            return keywords.Any(keyword => text.Contains(keyword, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 提取编号
        /// </summary>
        private static string? ExtractCode(string text, string[] prefixes)
        {
            foreach (var prefix in prefixes)
            {
                var pattern = $@"{prefix}[：:]\s*([A-Za-z0-9\-_]+)";
                var match = Regex.Match(text, pattern);
                if (match.Success)
                {
                    return match.Groups[1].Value;
                }
            }

            // 尝试提取引号中的内容
            var quotedMatch = Regex.Match(text, @"[""']([\w\-]+)[""']");
            if (quotedMatch.Success)
            {
                return quotedMatch.Groups[1].Value;
            }

            return null;
        }

        /// <summary>
        /// 提取名称
        /// </summary>
        private static string? ExtractName(string text, string[] prefixes)
        {
            foreach (var prefix in prefixes)
            {
                var pattern = $@"{prefix}[：:]\s*([^，,。.\n]+)";
                var match = Regex.Match(text, pattern);
                if (match.Success)
                {
                    return match.Groups[1].Value.Trim();
                }
            }

            // 尝试提取引号中的内容
            var quotedMatch = Regex.Match(text, @"[""']([^""']+)[""']");
            if (quotedMatch.Success)
            {
                return quotedMatch.Groups[1].Value;
            }

            return null;
        }
    }
}
